import { Space, Table } from "antd";
import { useEffect, useState } from "react";
import { ExclamationCircleFilled } from "@ant-design/icons";
import {
  getAllAuthority,
  ResetAuthority,
  checkAuthority,
  deleteAuthority,
} from "../../../../utils/httpAllMethods/AuthHttp.jsx";
import "./index.scss";
import { Form, Input, Button, message, Modal } from "antd";
import PageName from "../../../../components/PageName/index.jsx";
import { useNavigate } from "react-router-dom";
const { confirm } = Modal;
import { LoadingOutlined } from "@ant-design/icons";
import { parseTime } from "../../../../utils/date.jsx";
import debounce from "lodash.debounce";
const antIcon = (
  <LoadingOutlined
    style={{
      fontSize: 24,
    }}
    spin
  />
);
const Auth = () => {
  const [loading, setLoading] = useState(false);
  const [messageApi, contextHolder] = message.useMessage();
  const [form] = Form.useForm();
  const navigator = useNavigate();
  // 列数据
  const columns = [
    {
      title: "编号",
      dataIndex: "key",
      key: "key",
      align: "center",
    },
    {
      title: "账号",
      dataIndex: "admin",
      key: "admin",
      align: "center",
    },
    {
      title: "姓名",
      dataIndex: "name",
      key: "name",
      align: "center",
    },
    {
      title: "城市",
      dataIndex: "city",
      key: "city",
      align: "center",
    },
    {
      title: "权限",
      dataIndex: "auth",
      key: "auth",
      align: "center",
    },
    {
      title: "创建时间",
      dataIndex: "time",
      key: "time",
      align: "center",
      render: (_, { time }) => {
        return parseTime(time, "{y}-{m}-{d} {h}:{i}:{s}");
      },
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <a
            onClick={() => {
              editAuth(record);
            }}
          >
            编辑
          </a>
          <a
            onClick={() => {
              showDeleteConfirm("你确定重置密码吗?", record.key, "reset");
            }}
          >
            重置密码
          </a>
          <a
            onClick={() => {
              showDeleteConfirm("你确定删除此用户?", record.key, "delete");
            }}
          >
            删除
          </a>
        </Space>
      ),
    },
  ];
  const editAuth = ({ key }) => {
    navigator("/home/EditAuthority", { state: { id: key } });
  };
  // 显示成功信息
  const success = (content) => {
    messageApi.open({
      type: "success",
      content,
    });
  };
  // 显示错误信息
  const error = () => {
    messageApi.open({
      type: "error",
      content: "失败",
    });
  };
  const [data1, setData1] = useState([]);
  const [total, setTotal] = useState(1);
  // 获取首页数据
  const getData = () => {
    getAllAuthority().then((res) => {
      setTotal(res.data.length);
      setData1(
        res.data.map((item) => {
          return {
            key: item.admin_id,
            admin: item.admin_name,
            name: item.admin_nickname,
            city: item.admin_city,
            auth: getPermissionName(item.admin_authority.split(',')),
            time: item.createtime,
          };
        })
      );
    });
  };
  // 初始化加载
  useEffect(() => {
    getData();
  }, []);
  // 模态框
  const showDeleteConfirm = (title, Aid, action) => {
    confirm({
      title,
      icon: <ExclamationCircleFilled />,
      content: "",
      okText: "确认",
      okType: "danger",
      cancelText: "取消",
      onOk() {
        if (action == "reset") {
          ResetAuthority({ admin_id: Aid }).then((res) => {
            success(res.msg);
            getData();
          });
        } else {
          deleteAuthority({ admin_id: Aid }).then((res) => {
            success(res.msg);
            getData();
          });
        }
        getData();
      },
      onCancel() {
        error();
      },
    });
  };
  const getPermissionName = (permission) => {
    let auth =permission.map((e)=>{
      switch (e) {
        case "1":
          return '系统首页，';
        case "2":
          return "新房，";
        case "3":
          return "需求管理，";
        case "4":
          return "楼盘点评，";
        case "5":
          return "楼盘解读，";
        case "6":
          return "经纪人点评，";
        case "7":
          return "服务案例，";
        case "8":
          return "行业咨询，";
        case "9":
          return "红包活动，";
        case "10":
          return "焦点图，";
        case "11":
          return "广告，";
        case "12":
          return "个人用户，";
        case "13":
          return "经纪人，";
        case "14":
          return "城市区域，";
        case "15":
          return "轨道交通，";
        case "16":
          return "项目特色，";
        case "17":
          return "权限管理，";
  
        default:
          return "UNKNOWN PERMISSION";
      }
    })
    return auth
    
  };
  // 搜索信息
  const onSearchMsg = ({ admin }) => {
    form.resetFields();
    checkAuthority({ admin }).then((res) => {
      setTotal(res.data.length);
      setData1(
        res.data.map((item) => {
          return {
            key: item.admin_id,
            admin: item.admin_name,
            name: item.admin_nickname,
            city: item.admin_city,
            auth: getPermissionName(item.admin_authority.split(',')),
            time: item.createtime,
          };
        })
      );
     
      message.success("搜索成功!");
    });
  };
  // 重置信息
  const resetMsg = () => {
    getData();
    form.resetFields();
    message.success("清空成功!");
  };
  const AddAuthority = () => {
    navigator("/home/AddAuthority");
  };
  return (
    <>
      {contextHolder}
      <PageName name="用户列表" />
      <div className="action-box">
        <Form onFinish={onSearchMsg} form={form}>
          <div className="input-search">
            <Form.Item label="账号/姓名" name="admin">
              <Input />
            </Form.Item>
            <Button
              className="btn-action-this"
              type="primary"
              htmlType="submit"
            >
              搜索
            </Button>
            <Button
              className="btn-action-this"
              type="default"
              onClick={() => {
                debounce(resetMsg, 800)();
              }}
            >
              清空
            </Button>
          </div>
        </Form>
        <div className="btn-action">
          <Button
            className="btn-action-this"
            type="primary"
            onClick={AddAuthority}
          >
            添加
          </Button>
        </div>
      </div>
      <Table
        columns={columns}
        dataSource={data1}
        pagination={{
          defaultCurrent: 1,
          total,
          defaultPageSize: 5,
          hideOnSinglePage: true,
        }}
        rowKey={(record) => record.key}
      />
    </>
  );
};
export default Auth;
